package com.ziyun.erp.common.api;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ziyun.erp.common.utils.HttpClientUtil;
import io.renren.common.utils.StringUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * 高德api
 *
 * @author zh
 * @date 2018/7/2413:38
 */
public class GaoDeApi {
    private static final String KEY = "1ba8313010e77323a8ef231bf518af6b";

    private static String URL = "https://restapi.amap.com/v3";

    /**
     * 根据地址获取经纬度
     *
     * @param address
     * @return
     */
    public static Map getcodeGeo(String address) {
        Map rsMap = new HashMap();
        try {
            if (StringUtil.isEmpty(address)) {
                throw new RuntimeException("地址不能为空");
            }
            String httpUrl = URL + "/geocode/geo";
            Map mapQuery = new HashMap();
            mapQuery.put("address", address);
            mapQuery.put("key", KEY);
            String rs = HttpClientUtil.doGet(httpUrl, mapQuery);
            if (StringUtil.isEmpty(rs)) {
                throw new RuntimeException("接口请求失败");
            }
            JSONObject jsonObject = JSONObject.parseObject(rs);
            String status = jsonObject.getString("status");
            if (status.equals("1")) { //请求成功
                int count = jsonObject.getInteger("count");
                if (count == 0) { //未查询到匹配地址
                    rsMap.put("status", "error");
                    rsMap.put("data", "");
                    rsMap.put("msg", "未查询到匹配地址");
                } else if (count > 1) { //查询到多条数据 地址不准确
                    rsMap.put("status", "error");
                    rsMap.put("data", "");
                    rsMap.put("msg", "地址不准确");
                } else {
                    //只处理匹配一条记录的地址
                    JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                    String location = geocodes.getJSONObject(0).getString("location");
                    rsMap.put("status", "success");
                    rsMap.put("data", location);
                    rsMap.put("msg", "查询成功");
                }


            } else {//请求失败
                rsMap.put("status", "error");
                rsMap.put("data", "");
                rsMap.put("msg", jsonObject.getString("info"));
            }
            //System.out.println("rs:" + rs);

        } catch (Exception e) {
            rsMap.put("status", "error");
            rsMap.put("data", "");
            rsMap.put("msg", e.getMessage());
        }

        return rsMap;
    }

    /*public static void main(String args[]) {
        GaoDeApi gaoDeApi = new GaoDeApi();
        Map map =  getcodeGeo("浙江 杭州市 西湖区古墩路76号");
        System.out.println(map);
    }*/


}
